# -*- coding = utf-8 -*-
# @Author: Wchime
# @time: 2023/2/12 14:41
# @file: userViews.py
import datetime
import json
import time
import traceback

from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
from django.core.cache import cache
from django.core.paginator import Paginator
from django.shortcuts import render

from django.utils.decorators import method_decorator
from rest_framework.response import Response
from rest_framework.views import APIView

from goodsManage import models
from merchant import models as mc_models
from goodsManage.serializers import GoodsTypeSeriallizer, GoodsSeriallizer, HomeGoodsSeriallizer, \
    HomeRushGoodsSeriallizer, OrderSeriallizer
from logsManage.views import set_server_logs

from tools.authToken import create_token, userAuth
from tools.encryption import getSha256, getDataAes, setDataAes
from tools.log import logger
from tools.tool import get_ip, get_json_values, get_file_type, get_time_uid, delete_file, imgType_list

from Wchime import settings
from . import tasks


# 商品
from .tasks import rushtask, test


class Goods(APIView):
    # @method_decorator(userAuth)
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:

            ip = get_ip(request)
            body = request.query_params.dict()
            home = get_json_values("home", body)
            goodsId = get_json_values("id", body)
            class_name = get_json_values("class", body)
            search_info = get_json_values("search", body)
            search_dict = {}
            if goodsId:
                search_dict['id'] = goodsId
            if search_info:
                search_dict['name__icontains'] = search_info
            if class_name:
                search_dict['type__name__icontains'] = class_name

            goods = models.Goods.objects.filter(**search_dict)

            if home:
                # 没有推荐算法，直接给取随机数据
                number = int(get_json_values("number", body, 6))
                # print(number, type(number))
                goods = goods.order_by('?')[:number]
                seriallizer = HomeGoodsSeriallizer(goods, many=True)
                resp = {"code": 1, "data": seriallizer.data}
                return Response(resp)

            page_size = get_json_values("page_size", body, 10)
            page_num = get_json_values("page_num", body, 1)

            goods = goods.order_by('sort', 'id')
            paginator = Paginator(goods, page_size)
            goods = paginator.get_page(page_num)
            total = paginator.count

            seriallizer = HomeGoodsSeriallizer(goods, many=True)
            resp = {"code": 1, "data": seriallizer.data, 'total': total}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)


class RushGoods(APIView):
    # @method_decorator(userAuth)
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            # create_rushGoods()
            # userinfo = kwargs.get('userinfo')
            # user_id = userinfo.get('id')
            ip = get_ip(request)
            body = request.query_params.dict()
            home = get_json_values("home", body)
            goodsId = get_json_values("id", body)
            search_dict = {}
            if goodsId:
                search_dict['id'] = goodsId

            now = datetime.datetime.now().date()
            # print(now)

            goods = models.RushGoods.objects.filter(createtime__date=now, **search_dict)
            # print(goods)
            if home:
                # 没有推荐算法，直接给取随机数据
                number = int(get_json_values("number", body, 6))
                # print(number, type(number))
                goods = goods.order_by('id')[:number]
                seriallizer = HomeRushGoodsSeriallizer(goods, many=True)
                resp = {"code": 1, "data": seriallizer.data}
                return Response(resp)
            seriallizer = HomeRushGoodsSeriallizer(goods, many=True)
            resp = {"code": 1, "data": seriallizer.data}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)


class RushResult(APIView):
    def get(self, request):
        li = []
        body = request.query_params.dict()
        task_id = body.get('task_id')
        from celery import result
        ar = result.AsyncResult(task_id)
        # print("--------", ar)
        # print(ar.ready(), ar.state)
        # if ar.ready():
        #     print(ar.state, ar.get())
        if ar.state == 'SUCCESS':
            ret = ar.get()

            resp = {"code": 1, "data": ret}

        elif ar.state == "FAILURE" or ar.state == "REVOKED":

            resp = {"code": 1, "data": 0}
        else:

            resp = {"code": 1, "data": 0}

        return Response(resp)


class Order(APIView):
    @method_decorator(userAuth)
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:

            userinfo = kwargs.get('userinfo')
            user_id = userinfo.get('id')
            ip = get_ip(request)
            body = request.query_params.dict()
            home = get_json_values("home", body)
            merchant = get_json_values("merchant", body)
            search_dict = {}
            if merchant:
                from merchant import models as mer_md
                mer = mer_md.MerchantInfo.objects.filter(master_id=user_id).last()
                if mer:
                    search_dict['goods__master_id'] = mer.id
                else:
                    resp = {"code": 0, "data": li, 'msg': '您不是商家'}
                    return Response(resp)
                orders = models.Order.objects.filter(**search_dict).order_by('-createtime')
                seriallizer = OrderSeriallizer(orders, many=True)
                resp = {"code": 1, "data": seriallizer.data}
                return Response(resp)

            orders = models.Order.objects.filter(user_id=user_id).filter(**search_dict).order_by('-createtime')

            seriallizer = OrderSeriallizer(orders, many=True)
            resp = {"code": 1, "data": seriallizer.data}
        except Exception as e:
            print(traceback.format_exc())
            # logger.error(traceback.format_exc())
        return Response(resp)

    @method_decorator(userAuth)
    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            userinfo = kwargs.get('userinfo')
            user_id = userinfo.get('id')
            ip = get_ip(request)
            body = json.loads(request.body)
            # body = request.POST.dict()
            goods_id = get_json_values("goods_id", body)
            rush = get_json_values("rush", body)
            number = get_json_values("number", body, 1)
            rushgoods = get_json_values("rushgoods", body)

            if rush:
                rushgood = models.RushGoods.objects.filter(id=rushgoods).last()
                if rushgood:
                    if rushgood.number > 0:
                        t = rushtask.delay(user_id, rushgoods)
                        # t = test.delay()

                        resp = {"code": 1, "data": t.id, "msg": '抢购中'}
                    else:
                        resp = {"code": 1, "data": None, "msg": '已抢完'}
                #     price = rushgood.rushprice
                #     total = price * number
                #     if models.Order.objects.create(
                #             goods_id=rushgood.goods_id,
                #             price=price,
                #             number=number,
                #             total=total,
                #             user_id=user_id,
                #             isrush=1
                #     ):
                #
                #         resp = {"code": 1, "data": li, "msg": '新建成功'}
                #     else:
                #         resp = {"code": 0, "data": li, "msg": '新建失败'}

            else:
                good = models.Goods.objects.filter(id=goods_id).last()
                uid = get_time_uid()
                if good:
                    price = good.price
                    total = price * number
                    if models.Order.objects.create(
                            uid=uid,
                            goods_id=goods_id,
                            price=price,
                            number=number,
                            total=total,
                            user_id=user_id,
                    ):

                        resp = {"code": 1, "data": li, "msg": '新建成功'}
                    else:
                        resp = {"code": 0, "data": li, "msg": '新建失败'}

        except Exception as e:
            print(traceback.format_exc())
            logger.error(traceback.format_exc())
        return Response(resp)

